/* Grabber.m
*  Purpose:  This class grabs the contents of the screen under the 
*  grabberWindow and uses
*  it to create a TIFF file.
*
*  You may freely copy, distribute, and reuse the code in this example.
*  NeXT disclaims any warranty of any kind, expressed or  implied, as to 
*  its fitness for any particular use.
*/

#import "Grabber.h"
#import <appkit/NXBitmapImageRep.h>
#import <appkit/tiff.h>
#import <appkit/Window.h>
#import <appkit/View.h>
#import <dpsclient/wraps.h>

@implementation Grabber

- setGrabberWindow:anObject
{
    grabberWindow = anObject;

    /* Set the window level... */
    PSsetwindowlevel (100, [grabberWindow windowNum]);

    /* Without the next line the level doesn't seem to be set; */
    /* a window server bug. */
    [grabberWindow orderFront:nil];
    [grabberWindow display];
    return self;
}

- grab:sender
{
    NXRect grabRect;
    id bitmap;

    /* Grab the screen bits into the window. */
    PSsetautofill (NO, [grabberWindow windowNum]);
    [grabberWindow orderOut:nil];
    [grabberWindow orderFront:nil];

    /* Read the bits from the window */
    [[grabberWindow contentView] lockFocus];
    [[grabberWindow contentView] getBounds:&grabRect];
    bitmap = [[NXBitmapImageRep alloc] initData:NULL fromRect:&grabRect];
    [[grabberWindow contentView] unlockFocus];

    PSsetautofill (YES, [grabberWindow windowNum]);
    [grabberWindow display];

    if (bitmap) {
	NXStream *s = NXOpenMemory (NULL, 0, NX_READWRITE);
	printf ("spp %d bps %d w %d h %d\n",
		[bitmap samplesPerPixel],
		[bitmap bitsPerSample],
		[bitmap pixelsWide],
		[bitmap pixelsHigh]);
	if (s) {
	    [bitmap writeTIFF:s usingCompression:NX_TIFF_COMPRESSION_LZW];
	    NXFlush (s);
	    if (NXSaveToFile (s, "/tmp/screenshot.tiff")) {
		perror ("/tmp/screenshot.tiff");
	    } else {
		printf ("Image written to /tmp/screenshot.tiff\n");
	    }
	    NXCloseMemory (s, NX_FREEBUFFER);
	}
	[bitmap free];
    }

    return self;
}


@end
